import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { Department } from '../../models/Department';
import { DepartmentService } from '../../service/departmentService';

@Component({
  templateUrl: './departmentadd.html',
  styleUrls: ['./departmentadd.css']
})
export class DepartmentaddComponent implements OnInit, AfterViewChecked {
  messages = {
    departName: '',
    description: ''
  };

  constructor(
    private dialogRef: MatDialogRef<DepartmentaddComponent>,
    private departmentService: DepartmentService,
    @Inject(MAT_DIALOG_DATA) public department: Department
  ) {
    this.department = department || {};
  }
  @ViewChild('departmentForm')
  departmentForm: NgForm;

  ngAfterViewChecked() {
    if (this.departmentForm) {
      this.departmentForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {

  }
  onSubmit() {
    this.checkValidate(true);
    if (this.departmentForm.invalid) {
      // 触发mat的error
      this.departmentForm.onSubmit(null);
      return false;
    }

    if (this.department.id !== undefined) {
      this.departmentService.update(this.department).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    } else {
      this.departmentService.create(this.department).subscribe((res) => {
        this.dialogRef.close(res.res);
      });
    }
  }
  checkValidate(isSubmit?: boolean) {
    const form = this.departmentForm;

    for (const field in DepartmentaddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = DepartmentaddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }
  static ErrorMessages = {
    departName: {
      required: '部门名称不能为空'
    }
  };
}
